package com.example.houduan.controller;



import cn.hutool.crypto.SecureUtil;
import com.example.houduan.common.lang.RegisterUser;
import com.example.houduan.common.lang.Result;
import com.example.houduan.common.lang.common.EmailAndPassword;
import com.example.houduan.common.lang.common.LoginDto;
import com.example.houduan.common.lang.common.NameAndPassword;
import com.example.houduan.common.lang.mail.SendMail;
import com.example.houduan.entity.Blog;
import com.example.houduan.entity.User;
import com.example.houduan.service.BlogService;
import com.example.houduan.service.EvaService;
import com.example.houduan.service.TagService;
import com.example.houduan.service.UserService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 深林中的书海
 * @since 2021-02-05
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private EvaService evaService;
    @Autowired
    TagService tagService;
    @RequiresAuthentication
    @GetMapping("/index")
    public Object index() {
        User user = userService.getById(1);
        return Result.succ(200, "操作成功", user);
    }

    @PostMapping("/register")
    public Object register(@Validated @RequestBody RegisterUser reg) {
        String code= (String) redisTemplate.opsForValue().get(reg.getEmail());
        if(code==null){
            return Result.fail(422,"不存在验证码",null);
        }
        if(userService.checkByEmail(reg.getEmail())){
            return Result.fail(450,"该邮箱已经注册过账号",null);
        }
        if(userService.checkByUsername(reg.getUsername())!=null){
            return Result.fail(451,"该用户名已存在",null);
        }
        if (!code.equals(reg.getCode())){
            return Result.succ(420, "验证码错误",null);
        }
        if(reg.getCode().isEmpty()){
            return Result.succ(421, "验证码为空", null);
        }

        User user = new User(reg);
        userService.registerUser(user);
        redisTemplate.opsForValue().set(reg.getEmail(),0,Duration.ofSeconds(1L));
        return Result.succ(200, "注册成功", user);
    }

    @DeleteMapping("/logout/{id}")
    public Object logout(@PathVariable Long id,HttpServletRequest request) {
        String token=request.getHeader("token");
       User user= (User) redisTemplate.opsForValue().get(token);
       if(user!=null){
            if(user.equals(userService.findUserById(id))){
                List<Blog> m=blogService.getByusername(userService.findUserById(id).getUsername());
                for(Blog i:m){
                    tagService.removeById(i.getId());
                    evaService.delByid(i.getId());
                    blogService.removeById(i.getId());
                }
                evaService.delByusername(user.getUsername());
                blogService.delByusername(userService.findUserById(id).getUsername());
                userService.logoutUser(id);
                redisTemplate.opsForValue().set(token,user,Duration.ofSeconds(1L));
                return Result.succ(200, "删除成功", null);
            }else {
                return  Result.fail(420,"登录账号与注销账号不同",null);
            }


       }

        return Result.fail(400,"未登录",user);
    }

    @GetMapping("/getEmail/{email}")
    public Object email(@PathVariable String email) {
        SendMail sender = new SendMail();
        String a = sender.sendEmail(email);
        if(a.equals("邮件发送失败")){
            return Result.fail(420,"邮箱格式错误",a);
        }
        redisTemplate.opsForValue().set(email,a,Duration.ofMinutes(1L));
        return Result.succ(200, "验证码发送成功", a);
    }
    @PutMapping("/changePasswordByEmail")
    public Object change(@RequestBody EmailAndPassword emailAndPassword){
        String code= (String) redisTemplate.opsForValue().get(emailAndPassword.getEmail());
        if(code==null||emailAndPassword.getPassword()==null){
            return Result.fail(421,"参数不能为空",null);
        }
        if(!userService.checkByEmail(emailAndPassword.getEmail())){
            return Result.fail(450,"该邮箱未注册过账号",null);
        }
        if(!code.equals(emailAndPassword.getCode())){
            return Result.fail(420, "验证码错误", null);
        }
        userService.updatapassword(emailAndPassword.getEmail(),emailAndPassword.getPassword());
        return Result.succ(200,"密码成功修改",null);
    }
    @PutMapping("/changePasswordByPassword")
    public Object changeByPassword(@RequestBody NameAndPassword nameAndPassword){
        if(nameAndPassword.getName()==null||nameAndPassword.getOldpassword()!=null||nameAndPassword.getNewpassword()==null){
            return Result.fail(421,"参数不能为空",null);
        }
        if(userService.checkByUsername(nameAndPassword.getName())==null){
            return Result.fail(450,"不存在该用户名个账户",null);
        }
       if( userService.checkByUsername(nameAndPassword.getName()).getPassword().equals(SecureUtil.md5(nameAndPassword.getOldpassword()))){
           userService.updatapasswordByPassword(nameAndPassword.getName(),nameAndPassword.getOldpassword(),nameAndPassword.getNewpassword());
           return Result.succ(200,"密码成功修改",null);
       }
        return Result.fail(400,"密码错误",null);
    }
    @GetMapping(value = "/login")
    public Result login(@Validated @RequestBody LoginDto loginDto) {
        User user=userService.checkByUsername(loginDto.getUsername());
        user.setLastlogin(user.time());
        userService.updateUser(user);
        if(!SecureUtil.md5(loginDto.getPassword()).equals(user.getPassword())){
            return Result.fail(400,"密码错误",null);
        }
            String token=UUID.randomUUID()+"";
            redisTemplate.opsForValue().set(token,user, Duration.ofDays(7L));
            return Result.succ(200,"登陆成功",token);
    }
}

